<?php
namespace app\controller;

use app\BaseController;
use app\middleware\Auth;
use app\model\ChaozhuoAivideo;
use app\model\ChaozhuoAlarm;
use app\model\ChaozhuoEquiment;
use app\model\ChaozhuoEquimentRealtime;
use app\model\ChaozhuoFace;
use app\model\ChaozhuoFaceRecord;
use app\model\ChaozhuoInspect;
use app\model\ChaozhuoInspectMonthtable;
use app\model\ChaozhuoInspectRepairtable;
use app\model\ChaozhuoInspectServicedtable;
use app\model\ChaozhuoInspectWeektable;
use app\model\ChaozhuoProject;
use app\model\ChaozhuoTowercycle;
use app\model\ChaozhuoUploadfile;
use app\model\ChaozhuoUser;
use GuzzleHttp\Client;
use think\facade\Cache;
use think\facade\Filesystem;
use think\Request;

class WebController extends BaseController
{
    protected $middleware = [
        // 对所有方法应用 Auth 中间件，但排除 login 方法
        Auth::class => ['except' => ['login']],
    ];
    /* 获取云眸取流认证token */
    public function getYmToken(Request $request)
    {
        // Cache::delete('YmToken');
        $client = new Client();
        $url = 'https://api2.hik-cloud.com/oauth/token';
        $send = [
            "client_id" => env('ym_client_id'),
            "client_secret" => env('ym_client_secret'),
            "grant_type" => 'client_credentials',
        ];
        $access_token = Cache::get('YmToken');
        if ($access_token === null) {
            try {
                $response = $client->request('POST', $url, [
                    'form_params' => $send,
                ])->getBody();
                $data = json_decode($response, true);
                if (isset($data['access_token'])) {
                    $access_token = $data['access_token'];
                    Cache::set('YmToken', $access_token, 518400);
                } else {
                    return error('Failed to retrieve access token');
                }
            } catch (\GuzzleHttp\Exception\RequestException $e) {
                return fail('token fail');
            }
        }
        $client = new Client();
        $response = $client->get('https://api2.hik-cloud.com/v1/ezviz/account/info', [
            'headers' => [
                'Authorization' => 'Bearer ' . $access_token,
            ],
        ])->getBody();
        return success(json_decode($response, true)['data']);
    }
    /* 获取萤石云缓存 */
    public function getYsAccessToken(Request $request)
    {
        // Cache::delete('YS_AccessToken');
        $client = new Client();
        $url = 'https://open.ys7.com/api/lapp/token/get';
        $send = [
            "appKey" => env('YSappKey'),
            "appSecret" => env('YSappSecret'),
        ];
        $accessToken = Cache::get('YS_AccessToken');
        if ($accessToken === null) {
            try {
                $response = $client->request('POST', $url, [
                    'form_params' => $send,
                ])->getBody();
                $data = json_decode($response, true);
                if (isset($data['data']['accessToken'])) {
                    $accessToken = $data['data']['accessToken'];
                    Cache::set('YS_AccessToken', $accessToken, 518400);
                } else {
                    return error('Failed to retrieve access token');
                }
            } catch (\GuzzleHttp\Exception\RequestException $e) {
                return error('Request failed: ' . $e->getMessage());
            }
        }
        return success($accessToken);
    }
    /* 登录 */
    public function login(Request $request)
    {
        $authorization = $request->header('authorization');
        $where = [
            'account_number' => $request->post('account_number'),
            'password' => $request->post('password'),
        ];
        $user = ChaozhuoUser::where($where)->find();

        if ($user) {
            $user->token = $request->post('account_number');
            $user->save();
            $hidden = ['create_time', 'update_time', 'delete_time'];
            $user->hidden($hidden);
            Cache::set($user->token, $user, 86400);
            $user = Cache::get($user->token);
            return success($user);
        } else {
            return fail(null, '账号或密码错误');
        }
    }
    /* 项目相关 */
    public function projectList(Request $request)
    {
        $param = $request->param();
        $where = [];
        if ($request->has('pname', 'get', true)) {
            $pname = $request->param('pname');
            $where[] = ['pname', 'like', '%' . $param['pname'] . '%'];
        }
        if ($request->has('account_number', 'get', true)) {
            $account_number = $request->param('account_number');
            $where[] = ['account_number', 'like', '%' . $param['account_number'] . '%'];
        }
        // if ($request->has('uid', 'get', true)) {
        //     $uid = $request->param('uid');
        //     $where[] = ['uid', '=', $uid];
        // }
        // if ($request->user->identity == 'user') {
        //     $uid = $request->user->id;
        //     $where[] = ['uid', '=', $uid];
        // }
        $list = ChaozhuoProject::where($where)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    public function addProject(Request $request)
    {
        $param = $request->param();
        // $path = $param['path'];
        $appid = env('WX_AppID');
        $secret = env('WX_AppSecret');
        $client = new Client();
        $response = $client->get('https://api.weixin.qq.com/cgi-bin/token', [
            'query' => [ // 设置查询参数（URL 的参数部分）
                'grant_type' => 'client_credential',
                'appid' => $appid,
                'secret' => $secret,
            ],
        ]);
        $responseData = json_decode($response->getBody(), true);
        $accessToken = $responseData['access_token'];
        if ($request->has('id')) { //判断是否为添加
            $project = ChaozhuoProject::find($request->post('id'));
        } else {
            $project = new ChaozhuoProject;

        }
        if ($project) {
            foreach ($param as $key => $value) {
                $project->$key = $value;
            }
        }
        $rq = $project->save();
        if (!$request->has('id')) { //判断是否为添加
            // 获取小程序码
            $params = [
                'page' => 'pages/equipment/index',
                'scene' => $project->id,
                // 'scene' => 17,
                'check_path' => false,
                'env_version' => 'release',
            ];
            // return success($params);die;
            $client = new Client();
            $QR_address_response = $client->post('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $accessToken, [
                'json' => $params,
            ])->getBody()->getContents();
            // 生成文件名
            $fileName = 'qr/' . uniqid() . '.png';
            // 使用public磁盘进行存储
            $disk = Filesystem::disk('public');
            $disk->put($fileName, $QR_address_response);
            // 获取存储后的文件路径
            $relativeFilePath = $disk->getUrl($fileName);
            // 获取当前请求的域名
            $domain = request()->domain();
            // 拼接完整的可访问URL
            $filePath = $domain . $relativeFilePath;
            // 保存图片地址到数据库
            $project->QR_address = $filePath;
            $rq = $project->save();
        }

        if ($request->has('account_number')) { //判断是否为添加
            $ChaozhuoUser = ChaozhuoUser::where('pid', $project->id)->find();
            if (empty($ChaozhuoUser)) {
                $ChaozhuoUser = new ChaozhuoUser;
                $ChaozhuoUser->account_number = $request->post('account_number');
            }
            $ChaozhuoUser->password = $request->post('password');
            $ChaozhuoUser->pid = $project->id;
            $ChaozhuoUser->pname = $project->pname;
            $ChaozhuoUser->identity = 'project_user';
            $rq = $ChaozhuoUser->save();
        }
        $project->uid = $ChaozhuoUser->id;
        $rq = $project->save();
        return success($rq);
    }
    /* 删除用户 */
    public function reProject(Request $request)
    {
        $id = $request->param('id');
        $ChaozhuoProject = ChaozhuoProject::find($id);
        $uid = $ChaozhuoProject->uid;
        // $rq = $Resource->destroy($id);
        $rq = $ChaozhuoProject->delete(); //软删除
        if ($uid) {
            $ChaozhuoUser = ChaozhuoUser::find($uid);
            $rq = $ChaozhuoUser->delete(); //软删除
        }
        // $rq = $Resource->force()->delete(); //直接删除
        if ($rq) {
            return success($request);
        }
        return success($ChaozhuoEquiment);
    }
    public function addEquiment(Request $request)
    {
        $param = $request->param();

        if ($request->has('id')) { //判断是否为添加
            $ChaozhuoEquiment = ChaozhuoEquiment::find($request->post('id'));
        } else {
            $ChaozhuoEquiment = new ChaozhuoEquiment;

        }
        if ($ChaozhuoEquiment) {
            foreach ($param as $key => $value) {
                $ChaozhuoEquiment->$key = $value;
            }
        }
        if ($request->has('pid')) {
            $project = ChaozhuoProject::find($param['pid']);
            $ChaozhuoEquiment->pname = $project->pname;
        }

        $rq = $ChaozhuoEquiment->save();
        if (!$request->has('id')) { //判断是否为添加
            $appid = env('WX_AppID');
            $secret = env('WX_AppSecret');
            $client = new Client();
            $response = $client->get('https://api.weixin.qq.com/cgi-bin/token', [
                'query' => [ // 设置查询参数（URL 的参数部分）
                    'grant_type' => 'client_credential',
                    'appid' => $appid,
                    'secret' => $secret,
                ],
            ]);
            $responseData = json_decode($response->getBody(), true);
            $accessToken = $responseData['access_token'];
            // 获取小程序码
            $params = [
                'page' => 'pages/equipment/info/index',
                'scene' => $ChaozhuoEquiment->eid,
                // 'scene' => 17,
                'check_path' => false,
                'env_version' => 'release',
            ];
            // return success($params);die;
            $client = new Client();
            $QR_address_response = $client->post('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $accessToken, [
                'json' => $params,
            ])->getBody()->getContents();
            // 生成文件名
            $fileName = 'qr/' . uniqid() . '.png';
            // 使用public磁盘进行存储
            $disk = Filesystem::disk('public');
            $disk->put($fileName, $QR_address_response);
            // 获取存储后的文件路径
            $relativeFilePath = $disk->getUrl($fileName);
            // 获取当前请求的域名
            $domain = request()->domain();
            // 拼接完整的可访问URL
            $filePath = $domain . $relativeFilePath;
            // 保存图片地址到数据库
            $ChaozhuoEquiment->QR_address = $filePath;
            $rq = $ChaozhuoEquiment->save();
        }
        return success($ChaozhuoEquiment);
    }
    /* 设备项目列表 */
    public function equimentProjectList(Request $request)
    {
        $param = $request->param();
        $user = $request->user;
        $identity = $request->user->identity;
        $where = [];
        if ($request->has('pname', 'get', true)) {
            $pname = $request->param('pname');
            $where[] = ['pname', 'like', '%' . $param['pname'] . '%'];
        }
        if ($request->has('account_number', 'get', true)) {
            $account_number = $request->param('account_number');
            $where[] = ['account_number', 'like', '%' . $param['account_number'] . '%'];
        }
        if ($identity == 'project_user') {
            $where[] = $where[] = ['id', '=', $request->user->pid];
        }
        $fields = ['id', 'pname', 'adress', 'construction_unit'];
        $list = ChaozhuoProject::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    /* 设备列表 */
    public function equimentList(Request $request)
    {
        $param = $request->param();
        $user = $request->user;
        $identity = $request->user->identity;
        $where = [];
        if ($request->has('name', 'get', true)) {
            $name = $request->param('name');
            $where[] = ['name', 'like', '%' . $param['name'] . '%'];
        }
        if ($request->has('eid', 'get', true)) {
            $eid = $request->param('eid');
            $where[] = ['eid', 'like', '%' . $param['eid'] . '%'];
        }
        if ($request->has('online', 'get', true)) {
            $online = $request->param('online');
            $where[] = ['online', '=', $request->param('online')];
        }
        if ($request->has('alarm_status', 'get', true)) {
            $alarm_status = $request->param('alarm_status');
            $where[] = ['alarm_status', '=', $request->param('alarm_status')];
        }
        $where[] = ['pid', '=', $request->param('pid')];
        // $fields = ['id', 'name', 'eid', 'online', 'alarm_status'];
        $fields = ['*'];
        $list = ChaozhuoEquiment::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    /* 删除设备 */
    public function reEquiment(Request $request)
    {
        $param = $request->param();
        $ChaozhuoEquiment = ChaozhuoEquiment::find($request->post('id'));
        $ChaozhuoEquiment->pid = null;
        $ChaozhuoEquiment->name = null;
        $rq = $ChaozhuoEquiment->save();
        return success($ChaozhuoEquiment);
    }
    /* 设备列表 */
    public function equimentInfo(Request $request)
    {
        $param = $request->param();
        $ChaozhuoEquiment = ChaozhuoEquiment::where('eid', $param['eid'])->find();
        return success($ChaozhuoEquiment);
    }
    /* 塔机工作循环 */
    public function towerCycleList(Request $request)
    {
        $param = $request->param();
        $user = $request->user;
        $identity = $request->user->identity;
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        // 检查并添加结束时间条件
        if ($request->has('tower_start_time', 'get', true)) {
            $startTime = $request->param('tower_start_time');
            $where[] = ['tower_start_time', '>=', $startTime];
        }
        if ($request->has('tower_end_time', 'get', true)) {
            $endTime = $request->param('tower_end_time');
            $where[] = ['tower_end_time', '<=', $endTime];
        }

        $fields = ['*'];
        $list = ChaozhuoTowercycle::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    public function uploadFaceFile(Request $request)
    {
        $upload_url = env('UPLOAD_URL', true);
        $post = $request->post();
        $file = request()->file('file');
        //$文件名
        $fileName = $file->getOriginalName();
        $date = date('Y_m_d', time()); //当天日期
        $fileOssName = time() . $fileName; //阿里云文件名
        $ext = $file->getOriginalExtension(); //文件扩展名
        $ext = 'face';
        // $ossurl = config('filesystem.disks.aliyun.url');
        // 上传本地服务器
        $res = Filesystem::disk('public')->putFileAs($ext . '/' . $date, $file, $fileOssName); //按照文件类型分类
        $res = stripslashes($res); //去除转义字符
        $fileurl = 'https://' . $upload_url . '/' . $res;
        //地址存入数据库
        $upload = new ChaozhuoUploadfile;
        $upload->url = $fileurl;
        $upload->filename = $fileOssName;
        $upload->save();

        return success($fileurl);
    }
    public function addFace(Request $request)
    {
        $param = $request->param();
        if ($request->has('id')) { //判断是否为添加
            $ChaozhuoFace = ChaozhuoFace::find($request->post('id'));
        } else {
            $ChaozhuoFace = new ChaozhuoFace;

        }
        if ($ChaozhuoFace) {
            foreach ($param as $key => $value) {
                $ChaozhuoFace->$key = $value;
            }
        }
        $rq = $ChaozhuoFace->save();
        return success($ChaozhuoFace);
    }
    /* 删除人脸 */
    public function reFace(Request $request)
    {
        $id = $request->param('id');
        $Resource = ChaozhuoFace::find($id);
        // $rq = $Resource->destroy($id);
        $rq = $Resource->force()->delete(); //直接删除
        if ($rq) {
            return success($request);
        }
        return success($ChaozhuoEquiment);
    }
    public function faceRecordList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        // 检查并添加结束时间条件
        // if ($request->has('tower_start_time', 'get', true)) {
        //     $startTime = $request->param('tower_start_time');
        //     $where[] = ['tower_start_time', '>=', $startTime];
        // }
        $fields = ['*'];
        $list = ChaozhuoFaceRecord::where($where)->order('id desc')->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    public function faceList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        // 检查并添加结束时间条件
        // if ($request->has('tower_start_time', 'get', true)) {
        //     $startTime = $request->param('tower_start_time');
        //     $where[] = ['tower_start_time', '>=', $startTime];
        // }
        $fields = ['*'];
        $list = ChaozhuoFace::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    public function inspectList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        $where[] = ['type', '=', $request->param('type')];
        // 检查并添加结束时间条件
        // if ($request->has('tower_start_time', 'get', true)) {
        //     $startTime = $request->param('tower_start_time');
        //     $where[] = ['tower_start_time', '>=', $startTime];
        // }
        $fields = ['*'];
        $list = ChaozhuoInspect::where($where)->field($fields)->order('id', 'desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    /* 删除检修记录 */
    public function reInspect(Request $request)
    {
        $id = $request->param('id');
        $type = $request->param('type');
        $Resource = ChaozhuoInspect::find($id);
        // $rq = $Resource->destroy($id);
        // $rq = $Resource->force()->delete(); //直接删除
        $rq = $Resource->delete(); //直接删除
        switch ($type) {
            case 1:
                $Resource = ChaozhuoInspectWeektable::where('inspect_id', $id)->find();
                $rq = $Resource->delete(); //直接删除
                break;
            case 2:
                $Resource = ChaozhuoInspectMonthtable::where('inspect_id', $id)->find();
                $rq = $Resource->delete(); //直接删除
                break;
            case 3:
                $Resource = ChaozhuoInspectRepairtable::where('inspect_id', $id)->find();
                $rq = $Resource->delete(); //直接删除
                break;
            case 4:
                $Resource = ChaozhuoInspectServicedtable::where('inspect_id', $id)->find();
                $rq = $Resource->delete(); //直接删除
                break;
            default:
                break;
        }
        if ($rq) {
            return success($request);
        }
        return success($ChaozhuoEquiment);
    }
    /* 周检表格 */
    public function inspectWeektable(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['inspect_id', '=', $request->param('inspect_id')];
        $fields = ['*'];
        $list = ChaozhuoInspectWeektable::where($where)->field($fields)->find();

        $listArray = $list->toArray(); // 如果 $list 是对象，则首先转换为数组

        $filteredData = [];
        $towerInspectResult = [];

        foreach ($listArray as $key => $value) {
            if (strpos($key, 'tower_inspect_no') === 0 && strpos($key, '_result') !== false) {
                // 如果键名符合要求，则添加到 towerInspectResult 数组中
                $towerInspectResult[$key] = $value;
            } else {
                // 否则直接复制到 filteredData 中
                $filteredData[$key] = $value;
            }
        }
        $filteredData['tower_inspect_result'] = $towerInspectResult;
        return success($filteredData);
    }
    /* 月检表格 */
    public function inspectMonthtable(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['inspect_id', '=', $request->param('inspect_id')];
        $fields = ['*'];
        $list = ChaozhuoInspectMonthtable::where($where)->field($fields)->find();

        $listArray = $list->toArray(); // 如果 $list 是对象，则首先转换为数组

        $filteredData = [];
        $towerInspectResult = [];

        foreach ($listArray as $key => $value) {
            if (strpos($key, 'tower_inspect_no') === 0) {
                // 如果键名符合要求，则添加到 towerInspectResult 数组中
                $towerInspectResult[$key] = $value;
            } else {
                // 否则直接复制到 filteredData 中
                $filteredData[$key] = $value;
            }
        }
        $filteredData['tower_inspect_result'] = $towerInspectResult;
        return success($filteredData);
    }
    /* 检修表格 */
    public function inspectRepairtable(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['inspect_id', '=', $request->param('inspect_id')];
        $fields = ['*'];
        $list = ChaozhuoInspectRepairtable::where($where)->field($fields)->find();

        $listArray = $list->toArray(); // 如果 $list 是对象，则首先转换为数组

        $filteredData = [];
        $towerInspectResult = [];

        foreach ($listArray as $key => $value) {
            if (strpos($key, 'tower_inspect_no') === 0) {
                // 如果键名符合要求，则添加到 towerInspectResult 数组中
                $towerInspectResult[$key] = $value;
            } else {
                // 否则直接复制到 filteredData 中
                $filteredData[$key] = $value;
            }
        }
        $filteredData['tower_inspect_result'] = $towerInspectResult;
        return success($filteredData);
    }
    /* 报修表格 */
    public function inspectServicetable(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['inspect_id', '=', $request->param('inspect_id')];
        $fields = ['*'];
        $ChaozhuoInspectServicedtable = ChaozhuoInspectServicedtable::where($where)->field($fields)->find();
        return success($ChaozhuoInspectServicedtable);
    }
    /* 处理报修 */
    public function dealwithServicetable(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['inspect_id', '=', $request->param('id')];
        $fields = ['*'];
        $ChaozhuoInspect = ChaozhuoInspect::find($request->param('id'));
        $ChaozhuoInspectServicedtable = ChaozhuoInspectServicedtable::where($where)->find();
        $ChaozhuoInspect->is_dealwith = 1;
        $ChaozhuoInspect->save();
        $ChaozhuoInspectServicedtable->is_dealwith = 1;
        $rq = $ChaozhuoInspectServicedtable->save();
        return success($rq);
    }
    public function aiVideoList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        if ($request->has('start_time', 'get', true)) {
            $startTime = $request->param('start_time');
            $where[] = ['start_time', '>=', $startTime];
        }
        if ($request->has('end_time', 'get', true)) {
            $end_time = $request->param('end_time');
            $where[] = ['end_time', '<=', $end_time];
        }
        $fields = ['*'];
        $list = ChaozhuoAivideo::where($where)->order('id desc')->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    /* 请求下载AI视频 */
    public function downloadAiVideo(Request $request)
    {
        $param = $request->param();
        return success(true);
    }
    /* 请求下载AI报警视频 */
    public function downloadAlarmAiVideo(Request $request)
    {
        $param = $request->param();
        return success(true);
    }
    /* 删除AI视频记录 */
    public function reAiVideo(Request $request)
    {
        $id = $request->param('id');
        $Resource = ChaozhuoAivideo::find($id);
        // $rq = $Resource->destroy($id);
        $rq = $Resource->force()->delete(); //直接删除
        if ($rq) {
            return success($request);
        }
        return success($ChaozhuoEquiment);
    }
    /* 删除报警记录 */
    public function reAlarm(Request $request)
    {
        $id = $request->param('id');
        $Resource = ChaozhuoAlarm::find($id);
        // $rq = $Resource->destroy($id);
        $rq = $Resource->force()->delete(); //直接删除
        if ($rq) {
            return success($request);
        }
        return success($ChaozhuoEquiment);
    }
    /* 报警记录 */
    public function alarmList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        if ($request->has('start_time', 'get', true)) {
            $startTime = $request->param('start_time');
            $where[] = ['create_time', '>=', $startTime];
        }
        if ($request->has('end_time', 'get', true)) {
            $end_time = $request->param('end_time');
            $where[] = ['create_time', '<=', $end_time];
        }
        $fields = ['*'];
        $list = ChaozhuoAlarm::where($where)->order('id desc')->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    /* 实时数据 */
    public function realtimeList(Request $request)
    {
        $param = $request->param();
        $where = [];
        if ($request->has('eid', 'get', true)) {
            $eid = $request->param('eid');
            $where[] = ['eid', 'like', '%' . $param['eid'] . '%'];
        }
        if ($request->has('ename', 'get', true)) {
            $ename = $request->param('ename');
            $where[] = ['ename', 'like', '%' . $param['ename'] . '%'];
        }
        if ($request->has('pname', 'get', true)) {
            $pname = $request->param('pname');
            $where[] = ['pname', 'like', '%' . $param['pname'] . '%'];
        }
        if ($request->has('start_time', 'get', true)) {
            $startTime = $request->param('start_time');
            $where[] = ['create_time', '>=', $startTime];
        }
        if ($request->has('end_time', 'get', true)) {
            $end_time = $request->param('end_time');
            $where[] = ['create_time', '<=', $end_time];
        }
        $fields = ['*'];
        $list = ChaozhuoEquimentRealtime::where($where)->order('id desc')->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    /* 报修提醒 */
    public function inspectServiceRemind(Request $request)
    {
        $user = $request->user;
        $identity = $request->user->identity;
        $param = $request->param();
        $where = [];
        $where[] = ['is_dealwith', '=', 0];
        if ($identity != 'admin') {
            $where[] = ['pid', '=', $request->user->pid];
        }
        $fields = ['*'];
        $list = ChaozhuoInspectServicedtable::where($where)->field($fields)->order('id desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        // return success($user);
        return pageReturn($list);
    }
    /* EXCEL */
    public function exportCSV(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        // 检查并添加结束时间条件
        if ($request->has('tower_start_time', 'get', true)) {
            $startTime = $request->param('tower_start_time');
            $where[] = ['tower_start_time', '>=', $startTime];
        }
        if ($request->has('tower_end_time', 'get', true)) {
            $endTime = $request->param('tower_end_time');
            $where[] = ['tower_end_time', '<=', $endTime];
        }

        $fields = ['*'];
        $list = ChaozhuoTowercycle::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        $list = $list->toArray();
        // return success($list['data']);
        // return pageReturn($list);
        // 设置导出文件名
        $fileName = 'export_' . date('YmdHis') . '.csv';
        // $fileName = 'export_' . date('YmdHis') . '.xls';
        // 设置 HTTP 头信息
        header('Content-Type: text/csv');
        // header('Content-Type: text/xls');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        // 打开输出缓冲区
        $fp = fopen('php://output', 'w');
        // 写入表头
        fputcsv($fp, ['设备ID', '开始时间', '结束时间', '起始高度', '起始幅度', '起始回转角度', '起始吊重', '结束高度', '结束幅度', '结束回转角度', '结束吊重']);
        // 查询数据库数据
        // $dataList = Db::name('your_table')->select();
        // 写入数据
        foreach ($list['data'] as $item) {
            fputcsv($fp, [
                $item['eid'],
                $item['tower_start_time'],
                $item['tower_end_time'],
                $item['tower_start_height'],
                $item['tower_start_amplitude'],
                $item['tower_start_rotation'],
                $item['tower_start_load'],
                $item['tower_end_height'],
                $item['tower_end_amplitude'],
                $item['tower_end_rotation'],
                $item['tower_end_load'],
            ]);
        }
        // 关闭输出缓冲区
        fclose($fp);
        exit();
    }
    public function exportTowercycle(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        // 检查并添加结束时间条件
        if ($request->has('tower_start_time', 'get', true)) {
            $startTime = $request->param('tower_start_time');
            $where[] = ['tower_start_time', '>=', $startTime];
        }
        if ($request->has('tower_end_time', 'get', true)) {
            $endTime = $request->param('tower_end_time');
            $where[] = ['tower_end_time', '<=', $endTime];
        }

        $fields = ['*'];
        $list = ChaozhuoTowercycle::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        $list = $list->toArray();
        // return success($list['data']);
        // return pageReturn($list);
        // 设置导出文件名
        $fileName = 'export_' . date('YmdHis') . '.csv';
        // $fileName = 'export_' . date('YmdHis') . '.xls';
        // 设置 HTTP 头信息
        header('Content-Type: text/csv');
        // header('Content-Type: text/xls');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        // 打开输出缓冲区
        $fp = fopen('php://output', 'w');
        // 写入表头
        fputcsv($fp, ['设备ID', '开始时间', '结束时间', '起始高度', '起始幅度', '起始回转角度', '起始吊重', '结束高度', '结束幅度', '结束回转角度', '结束吊重']);
        // 查询数据库数据
        // $dataList = Db::name('your_table')->select();
        // 写入数据
        foreach ($list['data'] as $item) {
            fputcsv($fp, [
                $item['eid'],
                $item['tower_start_time'],
                $item['tower_end_time'],
                $item['tower_start_height'],
                $item['tower_start_amplitude'],
                $item['tower_start_rotation'],
                $item['tower_start_load'],
                $item['tower_end_height'],
                $item['tower_end_amplitude'],
                $item['tower_end_rotation'],
                $item['tower_end_load'],
            ]);
        }
        // 关闭输出缓冲区
        fclose($fp);
        exit();
    }
    public function exportAiVideo(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        // 检查并添加结束时间条件
        if ($request->has('tower_start_time', 'get', true)) {
            $startTime = $request->param('tower_start_time');
            $where[] = ['tower_start_time', '>=', $startTime];
        }
        if ($request->has('tower_end_time', 'get', true)) {
            $endTime = $request->param('tower_end_time');
            $where[] = ['tower_end_time', '<=', $endTime];
        }

        $fields = ['*'];
        $list = ChaozhuoAivideo::where($where)->order('id desc')->field($fields)->paginate(['list_rows' => $request->param('pageSize', 500), 'page' => $request->param('current', 1)]);
        $list = $list->toArray();
        // return success($list['data']);
        // return pageReturn($list);
        // 设置导出文件名
        $fileName = 'export_' . date('YmdHis') . '.csv';
        // $fileName = 'export_' . date('YmdHis') . '.xls';
        // 设置 HTTP 头信息
        header('Content-Type: text/csv');
        // header('Content-Type: text/xls');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        // 打开输出缓冲区
        $fp = fopen('php://output', 'w');
        // 写入表头
        fputcsv($fp, ['设备ID', '开始时间', '结束时间', '通道一', '通道二', '通道三', '通道四', '通道五', '通道六', '通道七', '通道八']);
        // 写入数据
        foreach ($list['data'] as $item) {
            fputcsv($fp, [
                $item['eid'],
                $item['start_time'],
                $item['end_time'],
                $item['channel_1_adress'],
                $item['channel_2_adress'],
                $item['channel_3_adress'],
                $item['channel_4_adress'],
                $item['channel_5_adress'],
                $item['channel_6_adress'],
                $item['channel_7_adress'],
                $item['channel_8_adress'],
            ]);
        }
        // 关闭输出缓冲区
        fclose($fp);
        exit();
    }
    public function exportAlarm(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        // 检查并添加结束时间条件
        if ($request->has('tower_start_time', 'get', true)) {
            $startTime = $request->param('tower_start_time');
            $where[] = ['tower_start_time', '>=', $startTime];
        }
        if ($request->has('tower_end_time', 'get', true)) {
            $endTime = $request->param('tower_end_time');
            $where[] = ['tower_end_time', '<=', $endTime];
        }

        $fields = ['*'];
        $list = ChaozhuoAlarm::where($where)->order('id desc')->field($fields)->paginate(['list_rows' => $request->param('pageSize', 500), 'page' => $request->param('current', 1)]);
        $list = $list->toArray();
        // return success($list['data']);
        // return pageReturn($list);
        // 设置导出文件名
        $fileName = 'export_' . date('YmdHis') . '.csv';
        // $fileName = 'export_' . date('YmdHis') . '.xls';
        // 设置 HTTP 头信息
        header('Content-Type: text/csv');
        // header('Content-Type: text/xls');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        // 打开输出缓冲区
        $fp = fopen('php://output', 'w');
        // 写入表头
        fputcsv($fp, ['设备编号', '报警时间', '报警项', '报警级别', '设备名称', '项目名称', '报警内容', '报警值']);
        //
        // 写入数据
        foreach ($list['data'] as $item) {
            fputcsv($fp, [
                $item['eid'],
                $item['create_time'],
                $item['alarm_item'],
                $item['alarm_level'],
                $item['ename'],
                $item['pname'],
                $item['alarm_content'],
                $item['alarm_value'],
            ]);
        }
        // 关闭输出缓冲区
        fclose($fp);
        exit();
    }
    /* 国标摄像头配置 */
    public function gb28181Config()
    {
        $param = $this->request->param(); //获取参数
        $where[] = ['eid', '=', $param['eid']];
        $ChaozhuoEquiment = ChaozhuoEquiment::where($where)->find();
        if (!$ChaozhuoEquiment) {
            return fail('设备不存在');
        }
        foreach ($param as $key => $value) {
            $ChaozhuoEquiment->$key = $value;
        }
        $ChaozhuoEquiment->save();
        return success($ChaozhuoEquiment);
    }
}
